package alo.p3;

public class function1 {

    public static void main(String[] args) {

    }



    //链表长度
    public int ListLength(ListNode headNode){
        int length=0;
        ListNode currentNode=headNode;
        while (currentNode!=null){
            length++;
            currentNode=currentNode.getNext();
        }
        return length;
    }

    //链表插入操作
    ListNode InsertInlinkedList(ListNode headNode, ListNode nodeToInsert, int position){
         if (headNode==null)
             return nodeToInsert;
         int size=ListLength(headNode);
         if (position>size+1||position<1){
             System.out.println("Position of node to insert is invalid. The valid inputs are 1 to"+(size+1));
             return headNode;
         }
         if (position==1){
             nodeToInsert.setNext(headNode);
             return nodeToInsert;
         } else {
             ListNode previousNode =headNode;
             int count=1;
             while (count<position-1){
                 previousNode=previousNode.getNext();
                 count++;
             }
             ListNode currentNode =previousNode.getNext();
             nodeToInsert.setNext(currentNode);
             previousNode.setNext(nodeToInsert);
         }
        return headNode;
    }

    //链表删除
    ListNode DeleteNodeFromLinkedList(ListNode headNode, int position){
        int size=ListLength(headNode);
        if (position>size||position<1){
            System.out.println("Position of node to delete is invalid.The valid inputs are 1 to"+size);
            return headNode;
        }
        if (position==1){
            ListNode currentNode = headNode.getNext();
            headNode=null;
            return currentNode;
        }else {
            ListNode previousNode = headNode;
            int count=1;
            while (count<position){
                previousNode=previousNode.getNext();
                count++;
            }
            ListNode currentNode=previousNode.getNext();
            previousNode.setNext(currentNode.getNext());
            currentNode=null;
        }
        return headNode;
    }

    //删除单向链表
    void DeleLinkedList(ListNode head){
        ListNode auxilaryNode,iterator=head;
        while (iterator!=null){
            auxilaryNode=iterator.getNext();
            iterator=null;    //在Java中，垃圾回收器将自动处理
            iterator=auxilaryNode; //在实际应用中，不需要实现此内容
        }
    }

}
